package com.chance.cc.crawler.development.command.meta.oauth;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import com.chance.cc.crawler.development.command.HttpCommand;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * created by CC on 2020/11/26
 * mail 279020185@qq.com
 */
@Slf4j
public class CrawlerOauthCommand extends HttpCommand {

    public CrawlerOauthCommand(String host, int port){
        super(host,port);
    }

    public HttpPage addOrUpdateUserOAuthInfo(List<Map<String,String>> crawlerUserOauthInfos,boolean isDeleteAll){
        String url = commandUrl("addOrUpdateUserOAuthInfo");
        url = url+"?isDeleteAll="+isDeleteAll;
        //compose crawler scheduler job
        //generate request
        HttpRequest request = new HttpRequest();
        request.setUrl(url);
        request.setMethod(HttpConstant.Method.POST);

        request.setRequestBody(HttpRequestBody.json(JSON.toJSONString(crawlerUserOauthInfos),"utf-8"));
        HttpPage httpPage = doCommand(request);
        log.info("add or update user oauth info result: {}",httpPage.getRawText());
        return httpPage;
    }

    public HttpPage addOrUpdateUserOAuthInfo(List<Map<String,String>> crawlerUserOauthInfos){

        return addOrUpdateUserOAuthInfo(crawlerUserOauthInfos,true);
    }

    public HttpPage queryUserOauthInfos(String domain){
        String url = commandUrl(domain+"/userOauthInfos");
        //compose crawler scheduler job
        //generate request
        HttpRequest request = new HttpRequest();
        request.setUrl(url);
        request.setMethod(HttpConstant.Method.GET);

        HttpPage httpPage = doCommand(request);
        log.info("query user oauth info result: {}",httpPage.getRawText());
        return httpPage;
    }

    @Override
    public String initUrlPrefix(String host,int port) {
        return StringUtils.join("http://",host,":",port,"/crawler/oauth/api/v1");
    }
}
